﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Data.SqlClient;
using System.Web;
using System.Security.Cryptography;
using System.Configuration;
using System.Data;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Web.UI.HtmlControls;
using System.Net;
//using BarcodeLib.Barcode;

public class Utility
{
    ////获取数据库连接字符串，其属于静态变量且只读，项目中所有文档可以直接使用，但不能修改
    //public static readonly string ConnectionStringLocalTransaction = ConfigurationManager.ConnectionStrings["default"].ConnectionString;
    public static readonly string ClientCode = ConfigurationManager.AppSettings["ClientCode"];
    public static readonly string keys = ConfigurationManager.AppSettings["keys"];
    public static readonly string siteHost = ConfigurationManager.AppSettings["siteHost"];

    /// <summary>
    /// 获得通过sql查询语句数据集
    /// </summary>
    /// <param name="sqlStr"></param>
    /// <param name="parms"></param>
    /// <returns></returns>
    //public static DataSet GetDataSet(string sqlStr, params SqlParameter[] parms)
    //{
    //    System.Data.SqlClient.SqlConnection Connection = new SqlConnection(ConnectionStringLocalTransaction);
    //    DataSet ds = new DataSet();
    //    using (Connection)
    //    {
    //        SqlCommand objSqlCommand = new SqlCommand(sqlStr, Connection);
    //        objSqlCommand.CommandType = CommandType.Text;
    //        if (parms != null)
    //        {
    //            for (int i = 0; i < parms.Length; i++)
    //            {
    //                objSqlCommand.Parameters.Add(parms[i]);
    //            }
    //        }
    //        SqlDataAdapter adapter = null;
    //        try
    //        {
    //            Connection.Open();
    //            adapter = new SqlDataAdapter(objSqlCommand);
    //            adapter.Fill(ds);
    //            Connection.Close();
    //        }
    //        catch (Exception e)
    //        {
    //            return ds;
    //        }
    //    }
    //    return ds;
    //}

    /// <summary>
    /// 获取登录服务器URL
    /// </summary>
    public static string LoginHost
    {
        get
        {
            return string.Format("http://{0}{1}", HttpContext.Current.Request.Url.Host,
                (HttpContext.Current.Request.Url.Port == 80 ? "" : ":" + HttpContext.Current.Request.Url.Port)) + (HttpContext.Current.Request.Url.Host.IndexOf("localhost")>=0?"/renwuzhixing":"");
        }
    }

    public static string GetEmpCodeUrl
    {
        get {
            return Trim(ConfigurationManager.AppSettings["GetEmpCodeUrl"]) ;
        }
    }

    public static string Trim(Object temp)
    {
        try
        {
            string t = temp.ToString().Trim();
            return t;
        }
        catch (Exception e)
        {
            return "";
        }
        
    }
    //请求地址
    public static string postrequest(string url, string body)
    {

        //定义request并设置request的路径
        WebRequest request = WebRequest.Create(url);
        request.Method = "post";

        //设置参数的编码格式，解决中文乱码
        byte[] byteArray = Encoding.UTF8.GetBytes(body);

        //设置request的MIME类型及内容长度
        request.ContentType = "application/json";
        request.ContentLength = byteArray.Length;

        //打开request字符流
        Stream dataStream = request.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();

        //定义response为前面的request响应
        WebResponse response = request.GetResponse();

        //获取相应的状态代码
        Console.WriteLine(((HttpWebResponse)response).StatusDescription);

        //定义response字符流
        dataStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(dataStream);
        string responseFromServer = reader.ReadToEnd();//读取所有
        return responseFromServer;
    }
      //md5加密
    public class SignHelper
    {
        public static string GetSign(string sb)
        {
            return GetMD5(sb.ToString());
        }
        public static string GetMD5(string str)
        {
            if (string.IsNullOrEmpty(str))
                return str;
            var sb = new StringBuilder(32);
            var md5 = System.Security.Cryptography.MD5.Create();
            var output = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
            for (int i = 0; i < output.Length; i++)
                sb.Append(output[i].ToString("X").PadLeft(2, '0'));
            return sb.ToString();
        }
    }
    //DateTime类型转换为时间戳(毫秒值)
    public static long DateToTicks(DateTime? time)
    {
        //return ((time.HasValue ? time.Value.Ticks : DateTime.Parse("1990-01-01").ToUniversalTime().Ticks) - 621355968000000000) / 10000;
        return (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000;
    }

    //时间戳(毫秒值)String转换为DateTime类型转换
    public static DateTime TicksToDate(string time)
    {
        return new DateTime((Convert.ToInt64(time) * 10000) + 621355968000000000);
    }
    public static string CovDate(Object date1,params string[] format)
    {
        DateTime dt;
        DateTime.TryParse(Trim(date1), out dt);
        if (dt is DBNull)
        {
            return "";
        }
        string strFormat = "yyyy-MM-dd";
        if (format.Length>0)
            strFormat = format[0];
        if (dt.ToString("yyyy-MM-dd") == "0001-01-01" || dt.ToString("yyyy-MM-dd") == "1900-01-01")
            return "";
        else
            return dt.ToString(strFormat);
    }

    public static int ToInt(Object temp)
    {
        int i = 0;
        int.TryParse(Trim(temp), out i);
        return i;

    }
    public static float Tofloat(Object temp)
    {
        float i = 0;
        float.TryParse(Trim(temp), out i);
        return i;

    }

    public static decimal ToDecimal(Object temp)
    {
        decimal i = 0;
        decimal.TryParse(Trim(temp), out i);
        return i;

    }

    /// <summary>
    /// 客户端提示信息

    /// <summary>
    /// 弹出信息
    /// </summary>
    public static void jsAlert(string message)
    {
        string js = "<script language=javascript>alert('{0}');</script>";
        HttpContext.Current.Response.Write(string.Format(js, message));
    }
    /// <summary>
    /// Unicode码转化成中文
    /// </summary>
    /// <param name="unicodeString"></param>
    /// <returns></returns>
    public static string ConvertToGB(string unicodeString)
    {
        string strGB = Regex.Unescape(unicodeString);
        return strGB;
    }

    /// <summary>
    /// 中文转化成Unicode码


    /// </summary>
    /// <param name="strGB"></param>
    /// <returns></returns>
    public static string ConvertToUnicode(string strGB)
    {
        char[] chs = strGB.ToCharArray();
        string result = string.Empty;
        foreach (char c in chs)
        {
            result += @"\u" + char.ConvertToUtf32(c.ToString(), 0).ToString("x");
        }
        return result;
    }


    /// <summary>
    /// 客户端提示信息

    /// </summary>
    /// <param name="alertstr">提示的信息</param>
    /// <param name="page">页面</param>
    public static void jsAlert(string alertstr, System.Web.UI.Page page)
    {
        string jsstr;
        jsstr = "<script language=" + Char.ConvertFromUtf32(34) + "javascript" + Char.ConvertFromUtf32(34) + ">alert('" + alertstr + "')</script>";
        if (!page.IsClientScriptBlockRegistered("jsalert"))
        {
            page.RegisterClientScriptBlock("jsalert", jsstr);
        }

    }
    /// <summary>
    /// 跳转回上一页

    /// </summary>
    /// <param name="path">路径</param>
    /// <param name="page">页面</param>
    public static void jsRedirect(string path, System.Web.UI.Page page)
    {
        string jsstr;
        jsstr = " <script language=" + Char.ConvertFromUtf32(34) + "javascript" + Char.ConvertFromUtf32(34) + ">window.location.href='" + path.Replace("+", "~~") + "'</script>";

        page.RegisterClientScriptBlock("jsRedirect", jsstr);

    }

    public static void ToErrorPage(Exception ex)
    {
        System.Web.SessionState.HttpSessionState session = HttpContext.Current.Session;
        session["exception"] = ex.Message;
        HttpContext.Current.Response.Redirect(LoginHost + "/Warning.aspx");
    }

    /// <summary>
    /// 用户登录
    /// </summary>
    /// <param name="UserName"></param>
    /// <param name="UserPwd"></param>
    /// <returns></returns>

    public static LoginUser CheckLogin(string userCode, string password)
    {
        LoginUser user = new LoginUser();
        try
        {
            string sql = @"select a.ID,a.loginid,a.username,a.password,a.role,a.phone from  [sys_users] a
 where a.Loginid = '" + userCode + "' and a.password = '" + password + "'";
            DataTable dtUser = DBHelper.ExecuteDataTable(sql);
            if (dtUser.Rows.Count > 0)
            {
                DataRow dr = dtUser.Rows[0];
                user.ID = ToInt(dr["id"]);
                user.LOGINID = Trim(dr["LOGINID"]);
                user.USERNAME = Trim(dr["USERNAME"]);
                user.PASSWORD = Trim(dr["PASSWORD"]);
                user.ROLE = Trim(dr["role"]);
                user.PHONE = Trim(dr["phone"]);
                LoginUser = user;
            }
        }
        catch (Exception)
        {
        }
        return user;
    }

    /// <summary>
    /// 获取登录的用户实体
    /// </summary>

    public static LoginUser LoginUser
    {
        get
        {
            LoginUser user = new LoginUser();
            if (Trim(HttpContext.Current.Session["loginUser"]) != "")
            {
                user = FromBinary<LoginUser>(Trim(HttpContext.Current.Session["loginUser"]));
            }
            return user;
        }
        set
        {
            HttpContext.Current.Session["loginUser"] = ToBinary<LoginUser>(value);
        }
    }

    /// <summary>
    /// 注销当前登录
    /// </summary>
    /// <param name="url">要跳到的登录页</param>
    public static void LogoutUser(string url)
    {
        HttpContext.Current.Session.Remove("loginUser");
        if (url != "")
            HttpContext.Current.Response.Redirect(url);
    }


    #region BinaryFormatter序列化
    /// <summary>
    /// BinaryFormatter序列化
    /// </summary>
    /// <param name="item">对象</param>
    public static string ToBinary<T>(T item)
    {
        BinaryFormatter formatter = new BinaryFormatter();
        using (MemoryStream ms = new MemoryStream())
        {
            formatter.Serialize(ms, item);
            ms.Position = 0;
            byte[] bytes = ms.ToArray();
            StringBuilder sb = new StringBuilder();
            foreach (byte bt in bytes)
            {
                sb.Append(string.Format("{0:X2}", bt));
            }
            return sb.ToString();
        }
    }

    /// <summary>
    /// BinaryFormatter反序列化
    /// </summary>
    /// <param name="str">字符串序列</param>
    public static T FromBinary<T>(string str)
    {
        int intLen = str.Length / 2;
        byte[] bytes = new byte[intLen];
        for (int i = 0; i < intLen; i++)
        {
            int ibyte = Convert.ToInt32(str.Substring(i * 2, 2), 16);
            bytes[i] = (byte)ibyte;
        }
        BinaryFormatter formatter = new BinaryFormatter();
        using (MemoryStream ms = new MemoryStream(bytes))
        {
            return (T)formatter.Deserialize(ms);
        }
    }
    #endregion

    public static void add_Cell(HtmlTableRow frow_MyRow, string fstr_Width, string fstr_Height, string fstr_Text, string fstr_Title, int fint_Colspan, string fstr_RGB, string fstr_align, string fstr_Class,
            int fint_Rowspan, string fstr_Event, string lint_Valign,string fstr_Color)
    {
        HtmlTableCell cel_TableCell = new HtmlTableCell();
        if (fstr_Width != "")
            cel_TableCell.Width = fstr_Width;
        if (fstr_Height != "")
        {
            cel_TableCell.Height = fstr_Height;
        }
        cel_TableCell.InnerHtml = fstr_Text;
        if (fstr_Title != "")
            cel_TableCell.Attributes.Add("title", fstr_Title);
        cel_TableCell.ColSpan = fint_Colspan;
        cel_TableCell.RowSpan = fint_Rowspan;
        cel_TableCell.VAlign = lint_Valign;
        if (fstr_RGB != "")
        {
            cel_TableCell.Attributes.Add("bgcolor", fstr_RGB);
        }
        if (fstr_Color != "")
        {
            cel_TableCell.Style.Add(System.Web.UI.HtmlTextWriterStyle.Color, fstr_Color);
        }
        if (fstr_align == "")
            fstr_align = "left";
        cel_TableCell.Attributes.Add("align", fstr_align);
        if (fstr_Class != "")
            cel_TableCell.Attributes.Add("class", fstr_Class);
        if (fstr_Event != "")
        {
            cel_TableCell.Attributes.Add("onmouseover", fstr_Event);
        }
        frow_MyRow.Cells.Add(cel_TableCell);
        cel_TableCell = null;
    }

    //public static void GetBarcode(int height, int width, string code, string fileName)
    //{
    //    try
    //    {
    //        BarcodeLib.Barcode.Linear codabar = new BarcodeLib.Barcode.Linear();
    //        codabar.Type = BarcodeType.CODE128A;
    //        codabar.Data = code;

    //        codabar.UOM = UnitOfMeasure.PIXEL;
    //        codabar.BarColor = System.Drawing.Color.FromArgb(0x00, 0x00, 0x33);
    //        codabar.BarWidth = 2;
    //        codabar.BarHeight = 40;
    //        codabar.LeftMargin = 0;
    //        codabar.RightMargin = 0;
    //        codabar.ImageWidth = width;
    //        //codabar.ImageHeight = height;
    //        codabar.drawBarcode(fileName);
    //    }
    //    catch (Exception ex)
    //    {
    //    }
    //}  

}